package com.moose.operator.web.service.impl.oauth;

import com.moose.operator.constant.AuthTypeConstant;
import com.moose.operator.constant.ThirdPartUrlConstant;
import com.moose.operator.exception.BusinessException;
import com.moose.operator.model.api.ResultCode;
import com.moose.operator.model.dto.GithubUserInfoDTO;
import com.moose.operator.util.OkHttpClientUtils;
import com.moose.operator.web.service.AuthService;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @author taohua
 */

@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

  @Override public String genThirdPartUrl(String type) {
    if (AuthTypeConstant.GITHUB.equals(type)) {
      return genGithubUrl();
    }
    return null;
  }

  @Override public GithubUserInfoDTO authGithub(String code) {
    Map<String, String> params = new HashMap<>(16);
    params.put("client_id", "d1bc73fd14e5decb64a4");
    params.put("client_secret", "7ad1c29356af2d5cf0389939c684b81e82c9a492");
    params.put("code", code);
    Response tokenRes = OkHttpClientUtils.getInstance()
        .postData(ThirdPartUrlConstant.GITHUB_ACCESS_TOKEN_URL, params);
    String tokenStr = null;
    try {
      tokenStr = Objects.requireNonNull(tokenRes.body()).string();
    } catch (Exception e) {
      log.error("请求 [{}] 失败 [{}]", ThirdPartUrlConstant.GITHUB_ACCESS_TOKEN_URL, e.getMessage());
      throw new BusinessException(ResultCode.THIRD_PART_LOGIN_FAIL);
    }
    if (StringUtils.isEmpty(tokenStr)) {
      throw new BusinessException(ResultCode.THIRD_PART_LOGIN_FAIL);
    }
    String token = this.checkGithubToken(tokenStr);
    if (StringUtils.isEmpty(token)) {
      throw new BusinessException(ResultCode.THIRD_PART_LOGIN_FAIL);
    }

    Map<String, String> headerParams = new HashMap<>(16);
    headerParams.put("Authorization", "token " + token);
    Response userRes = OkHttpClientUtils.getInstance()
        .postData(ThirdPartUrlConstant.GITHUB_USER_INFO_URL, headerParams, null);

    if (userRes.body() != null) {
      //GithubUserInfoDTO githubUserInfoDTO = new GithubUserInfoDTO();
      try {
        String jsonString = Objects.requireNonNull(userRes.body()).string();
        log.info("userStr {}", jsonString);
        //  Map<String, Object> map = MapperUtils.json2map(userStr);
        //  githubUserInfoDTO.setAvatarUrl((String) map.get("avatar_url"));
        //  githubUserInfoDTO.setBio((String) map.get("bio"));
        //  githubUserInfoDTO.setEmail((String) map.get("email"));
        //  githubUserInfoDTO.setId((String) map.get("id"));
        //  githubUserInfoDTO.setName((String) map.get("name"));
        //  log.error("请求结果 [{}]", MapperUtils.obj2json(githubUserInfoDTO));
      } catch (Exception e) {
        e.printStackTrace();
      }
      //return githubUserInfoDTO;
    }
    return null;
  }

  private String genGithubUrl() {
    return "https://github.com/login/oauth/authorize?client_id=d1bc73fd14e5decb64a4&redirect_uri=http://moose.com:8000/auth/callback";
  }

  private String checkGithubToken(String str) {
    String[] splits = str.split("&");
    if (splits.length > 0) {
      String[] split = splits[0].split("=");
      if (split.length > 0) {
        return split[1];
      }
    }
    return null;
  }
}
